namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Web.Mvc;
    using SimpleWebServices.Globalization;
    using SimpleWebServices.Web.Routing;

    public abstract class UriConverter
    {
        protected UriConverter(Type controller)
        {
            if (null == controller)
            {
                throw new ArgumentNullException("controller");
            }
            else if (!typeof(IController).IsAssignableFrom(controller))
            {
                throw new ArgumentOutOfRangeException("controller");
            }

            this.Controller = controller;
        }

        private Type Controller
        {
            get;
            set;
        }

        public virtual ResourcePath ToResourcePath(string path)
        {
            if (null == path)
            {
                throw new ArgumentNullException("path");
            }
            else if (0 == path.Length)
            {
                throw new ArgumentOutOfRangeException("path");
            }

            foreach (var method in this.Controller.GetMethods())
            {
                foreach (object attribute in method.GetCustomAttributes(typeof(ContentNegotiationAttribute), true))
                {
                    string extension = "." + (attribute as ContentNegotiationAttribute).Extension;
                    if (path.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                    {
                        path = path.Substring(0, path.Length - extension.Length);
                    }
                }
            }

            return path;
        }

        protected static Language ToLanguage(string path)
        {
            Language result = null;

            if (null != path)
            {
                string value = null;
                if (3 < path.Length && '.' == path[path.Length - 3])
                {
                    value = path.Substring(path.Length - 2);
                }
                else if (5 < path.Length && '.' == path[path.Length - 6] && '-' == path[path.Length - 3])
                {
                    value = path.Substring(path.Length - 5);
                }

                if (Language.IsValid(value))
                {
                    result = value;
                }
            }

            return result;
        }
    }
}